package cn.iocoder.yudao.module.asasc.common;

import cn.iocoder.yudao.module.asasc.dal.dataobject.salesreport.SalesReportDO;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Base64;

public class AppUtils {
    /**
     * 生成 hash 值
     *
     * @param obj
     * @return
     */
    public static String  objString(Object obj) {
        if (obj == null) {
            throw new IllegalArgumentException("Object cannot be null");
        }

        StringBuilder sb = new StringBuilder();
        Field[] fields = obj.getClass().getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            field.setAccessible(true);
            try {
                Object value = field.get(obj);
                if (value != null) {
                    sb.append(value);
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Failed to access field value", e);
            }
        });

        System.out.println(sb);
        return sb.toString();
    }

    // 生成随机盐值
    private static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 生成哈希值
    private static String hashString(String input, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            String inputWithSalt = input + salt;
            byte[] hash = md.digest(inputWithSalt.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("No such hashing algorithm", e);
        }
    }

    // 示例方法：生成带盐值的哈希
    public static String generateHashWithSalt(Object obj, String salt) {
        return hashString(objString(obj), salt);
    }

    // 示例方法：生成不带盐值的哈希
    public static String generateHash(Object obj) {
        return hashString(objString(obj), "");
    }

    public static void main(String[] args) {
        SalesReportDO salesReport = new SalesReportDO();
        salesReport.setId(1);
        salesReport.setCategory("1.0");
        salesReport.setCountryCode("CN");
        salesReport.setBeginDate(LocalDate.parse("2024-01-01"));
        System.out.println(generateHashWithSalt(salesReport, "sku"));
        System.out.println(generateHash(salesReport));
    }
}
